package com.hll.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hll.api.config.web.RespMessage;
import com.hll.api.enums.SMS;
import com.hll.api.exception.MyException;
import com.hll.api.service.XinhuaService;
import com.hll.api.util.HttpRequestUtil;
import com.hll.api.util.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author 何龙
 * @create 2019-07-09 22:08
 */
@Service
public class XinhuaServiceImpl implements XinhuaService {

	private static final String URL="http://m.xhsd.com/api/design/page/get-design-data";

	@Override
	public JSONObject getClassification() {
		return getResult("?release=1&path=%2Fcategory&appType=mobile&parts=%5B%7B%22partKey%22%3A%22body%22%7D%5D");
	}

	@Override
	public JSONObject getIndex() {
		return getResult("?release=1&path=%2Findex&appType=mobile&parts=%5B%7B%22partKey%22%3A%22body%22%7D%5D");
	}

	@Override
	public JSONObject getFindWords() {
		String s;
		try {
			s = HttpUtils.get("http://m.xhsd.com/api/misc/app/img/findWords?size=15&clientType=1");
		} catch (Exception e) {
			throw new MyException("请求失败");
		}
		if (StringUtils.isEmpty(s)){
			throw new MyException("接口请求超时");
		}

		JSONObject json = JSONObject.parseObject(s);
		if (json.getBoolean("success")){
			return json.getJSONObject("data");
		}else {
			throw new MyException("接口请求异常");
		}
	}

	@Override
	public JSONObject getCarouselInfo(String name) {
		return getResult("?release=1&appType=mobile&parts=%5B%7B%22partKey%22%3A%22body%22%7D%5D&path=%2Factivity%2F"+name);
	}

	@Override
	public JSONObject getSellWellRanking() {
		return getResult("?release=1&path=%2Factivity%2F2018top&appType=mobile&parts=%5B%7B%22partKey%22%3A%22body%22%7D%5D");
	}

	@Override
	public JSONObject getMonographic() {
		return getResult("?release=1&path=%2Factivity%2Fzhuanti-more&appType=mobile&parts=%5B%7B%22partKey%22%3A%22body%22%7D%5D");
	}

	@Override
	public JSONObject getCoupon() {
		return getResult("?release=1&path=%2Factivity%2Fcoupons&appType=mobile&parts=%5B%7B%22partKey%22%3A%22body%22%7D%5D");
	}

	@Override
	public JSONObject getActivity(String path) {
		return getResult("?release=1&appType=mobile&parts=%5B%7B%22partKey%22%3A%22body%22%7D%5D&path=%2Factivity%2F"+path);
	}

	@Override
	public JSONArray getPrompt(String keyword) throws MyException {
		String s;
		try {
			s = HttpRequestUtil.get("http://m.xhsd.com/api/item/mall/suggest?keyword=" + keyword);
		} catch (Exception e) {
			throw new MyException(e.getMessage());
		}
		if (StringUtils.isEmpty(s)){
			throw new MyException("接口请求超时");
		}
		return JSON.parseObject(s).getJSONArray("data");
	}

	@Override
	public JSONObject getSearchList(Integer pageNo, Integer pageSize, boolean includeEbook, String keyword,
	                                Float lowPrice, Float highPrice, Integer sort, String tenantId, String brandIds,
	                                String regionIds, String backCategoryIds, String frontCategoryId, String shopId,
	                                String shopCategoryId, String attributes, String ids, String types, String itemCode,
	                                Integer inStock) {
		Map<String,Object> map = new HashMap<>(20);
		map.put("pageNo",pageNo);
		map.put("pageSize",pageSize);
		map.put("includeEbook",includeEbook);
		map.put("keyword",keyword);
		map.put("lowPrice",lowPrice==null?null:(Math.round(lowPrice*100)/100)*100);
		map.put("highPrice",highPrice==null?null:(Math.round(highPrice*100)/100)*100);
		map.put("sort",sort);
		map.put("tenantId",tenantId);
		map.put("brandIds",brandIds);
		map.put("regionIds",regionIds);
		map.put("backCategoryIds",backCategoryIds);
		map.put("frontCategoryId",frontCategoryId);
		map.put("shopId",shopId);
		map.put("shopCategoryId",shopCategoryId);
		map.put("attributes",attributes);
		map.put("ids",ids);
		map.put("types",types);
		map.put("itemCode",itemCode);
		map.put("inStock",inStock);
		String s;
		try {
			s = HttpRequestUtil.get("http://m.xhsd.com/api/item/mall/search" + getParm(map));
		} catch (Exception e) {
			throw new MyException(e.getMessage());
		}
		if (StringUtils.isEmpty(s)){
			throw new MyException("接口请求超时");
		}
		return JSON.parseObject(s).getJSONObject("data");
	}

	@Override
	public JSONObject getProductDetails(String itemId) throws MyException {
		Map<String,Object> map = new HashMap<>(6);
		map.put("provinceId","110000");
		map.put("cityId","110100");
		map.put("districtId","110105");
		map.put("itemId",itemId);
		map.put("clientType","web");
		map.put("_:",System.currentTimeMillis());
		String s;
		try {
			s=HttpUtils.get("http://m.xhsd.com/api/yanan/item/wapItemDetail", map);
		} catch (Exception e) {
			throw new MyException("请求接口失败");
		}
		if (StringUtils.isEmpty(s)){
			throw new MyException("网络超时");
		}
		JSONObject jsonObject = JSON.parseObject(s);
		if (jsonObject.getBoolean("success")){
			return jsonObject.getJSONObject("data");
		}else {
			throw new MyException("请求失败");
		}

	}

	@Override
	public JSONObject getOtherData(String itemId) throws Exception {
		String s = HttpUtils.get("http://m.xhsd.com/api/item/otherData?itemId=" + itemId);
		return JSON.parseObject(s);
	}

	@Override
	public JSONObject getOtherCategory(String itemId) throws Exception {
		String s = HttpUtils.get("http://m.xhsd.com/api/item/outer-category/" + itemId);
		JSONObject jsonObject = JSON.parseObject(s);
		if (jsonObject.getBoolean("success")){
			return jsonObject.getJSONObject("data");
		}
		throw new MyException("请求失败");
	}

	@Override
	public byte[] getImg(String imgUrl) throws Exception {
		if (imgUrl.startsWith("https")){
			return HttpUtils.getSSLImg(imgUrl);
		}else if (imgUrl.startsWith("http")){
			return HttpUtils.getImg(imgUrl);
		}
		return new byte[0];
	}

	private static final String SMS_URL ="http://apis.haoservice.com/sms/send";
	private static final String SMS_KEY ="097bc857a4514a9d82427835243cd898";

	@Override
	public RespMessage endsms(SMS sms, String mobile) throws Exception {
		RespMessage respMessage;
		Map<String,Object> map=new HashMap<>(6);
		map.put("key", SMS_KEY);
		map.put("mobile",mobile);
		map.put("tpl_id",sms.getCode());
		map.put("paybyvas",false);
		String code = generateString();
		switch (sms){
			case THECANCELLATION:
			case THE_LOGIN:
			case REGISTERED:
			case CHANGE_PASSWORD: {
				map.put("tpl_value","%23code%23%3d" + code);
			}break;
			case SUCCESS:{
				map.put("tpl_value","%23code%23%3d"+mobile+"%26%23pass%23%3d" +mobile);
			}break;
			default: throw new MyException("类型错误");
		}
		String s = HttpRequestUtil.get(SMS_URL+getParm(map));
		JSONObject object = JSON.parseObject(s);
		if (object.getIntValue("error_code")==0){
			return RespMessage.success(code,"");
		}else {
			return RespMessage.error(object.getString("reason"));
		}
	}

	@Override
	public JSONObject getSmsNum() {
		Map<String,Object> map=new HashMap<>(6);
		map.put("key", SMS_KEY);
		map.put("paybyvas",false);
		String s = HttpRequestUtil.get("http://apis.haoservice.com/sms/status"+getParm(map));
		return JSON.parseObject(s);
	}


	/**
	 * 公共参数
	 * @param parameter 参数
	 * @return json结果
	 */
	private JSONObject getResult(String parameter){
		String result;
		try {
			result = HttpUtils.post(URL+parameter);
		} catch (Exception e) {
			throw new MyException("请求失败");
		}
		if (StringUtils.isEmpty(result)){
			throw new MyException("请求失败");
		}
		return JSON.parseObject(result);
	}

	private String getParm(Map<String,Object> list) {
		StringBuilder buffer = new StringBuilder("?");
		for (Map.Entry<String, Object> entry : list.entrySet()) {
			if (entry.getValue()!=null){
				buffer.append(entry.getKey()).append("=").append(entry.getValue().toString()).append("&");
			}
		}
		return buffer.toString();
	}


	private static final String ALL_CHAR = "0123456789";

	/**
	 * 随机数
	 */
	private static String generateString() {
		StringBuilder sb = new StringBuilder();
		Random random = new Random();
		for (int i = 0; i < 6; i++) {
			sb.append(ALL_CHAR.charAt(random.nextInt(ALL_CHAR.length())));
		}
		return sb.toString();
	}
}
